<template>
  <div class="login-container">
    <div class="login-box">
      <div class="left-side">
        <img src="../assets/vue.svg" alt="Logo" class="logo" />
        <h4 class="project-name">综合市场<br>管理</h4>
      </div>
      <div class="right-side">
          <div v-if="isLogin" key="login" class="form-container">
            <el-form
                :model="loginForm" status-icon :rules="loginRules" ref="loginFormRef" label-width="auto" class="login-form">
              <h2>欢迎使用</h2>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" type="text" autocomplete="off" />
              </el-form-item>
              <el-form-item label="密&nbsp;&nbsp;&nbsp; 码" prop="password">
                <el-input v-model="loginForm.password" type="password" autocomplete="off" />
              </el-form-item>
              <el-form-item label="验证码" prop="captcha">
                <el-input v-model="loginForm.captcha">
                  <template #append>
                    <img :src="chapter" style="height: 30px;" @click="getCode" alt="验证码"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
<!--                <el-checkbox v-model="checked" label="记住我" size="large" />-->
                <el-button class="login-btn" type="primary" size="large" @click="submitForm(loginFormRef)">登录</el-button>
                <el-button class="register-btn" size="large" @click="toRegister()">注册/入驻</el-button>
              </el-form-item>
            </el-form>
          </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
    import {reactive, ref} from 'vue'
    import {ElMessage, FormInstance, FormRules} from 'element-plus'
    import {useRouter} from 'vue-router';
    import {getChapter, userLogin} from "../api/login";
    import {sysStore} from "../stores";

    const router = useRouter();
    const isLogin = ref(true);
    const loginFormRef = ref<FormInstance>()
    const chapter = ref('')
    const appStore = sysStore();

    const loginForm = reactive({
      username: 'admin',
      password: '123456',
      captcha: '',
    })

    const checkUsername = (_rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入用户名!'))
      }
      callback()
    }

    const checkPassword = (_rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入密码!'))
      }
      callback()
    }

    const checkLogCaptcha = (_rule: any, value: any, callback: any) => {
      if (!value) {
        callback(new Error('请输入验证码!'))
      }
      callback()
    }

    const loginRules = reactive<FormRules<typeof loginForm>>({
      username: [{ validator: checkUsername, trigger: 'blur' }],
      password: [{ validator: checkPassword, trigger: 'blur' }],
      captcha: [{ validator: checkLogCaptcha, trigger: 'blur' }],
    });

    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate(async (valid) => {
        if (valid) {
          const res = await userLogin({
            username: loginForm.username,
            password: loginForm.password,
            chapter: loginForm.captcha,
          })
          if (res.code == 200) {
            ElMessage.success('登录成功!')
            localStorage.setItem('AccessToken', res.data.AccessToken)
            localStorage.setItem('RefreshToken', res.data.RefreshToken)
            const user = res.data.User
            appStore.setUser(user)
            appStore.permissions = res.data.Permissions
            await router.push({
              path: '/main'
            })
          }else {
            ElMessage.error(res.message)
          }
        }
      });
    };

    const getCode = async () => {
      const response = await getChapter()
      const urlCreator = window.URL || (window as any).webkitURL
      chapter.value = urlCreator.createObjectURL(new Blob([response]))
    }
    getCode()

    const toRegister = () => {
      router.push({ path: '/register' });
    };
</script>

<style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: white url('../assets/login.jpg') no-repeat center / cover;
  }

  .login-box{
    display: flex;
    width: 640px;
    height: 420px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
  }

  .left-side, .right-side {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;
    border-radius: 8px;
  }

  .logo {
    width: 168px;
    height: auto;
    margin-top: 10px;
  }

  .project-name {
    font-size: 2.5em;
    text-align: center;
    color: white;
  }

  .left-side{
    width: 40%;
    background-color: #42d392;
  }

  .right-side {
    width: 60%;
    background-color: #fff;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
    padding: 20px;
    border-radius: 8px;
  }

  .login-form {
    width: 100%;
  }

  .login-form h2 {
    margin-bottom: 20px;
    color: #42d392;
    text-align: center;
  }

  .login-btn{
    width: 100%;
    margin: 10px;
    background-color: #42d392;
    border: none;
    border-radius: 4px;
    color: white;
    font-size: 18px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .login-btn:hover {
    background-color: #94b3e2;
  }

  .register-btn{
    width: 100%;
    margin: 10px;
    background-color: #9a9595;
    border: none;
    border-radius: 4px;
    color: white;
    font-size: 18px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .register-btn:hover {
    background-color: #94b3e2;
  }
</style>